<?php

if (strlen(@$_REQUEST['q']) > 0)
{
	$term = $_REQUEST['q'];
}
else 
{
	$term = @$_REQUEST['function'];
}

// check if the search is for a players username or id number
if (is_numeric($term)) 
{ 
    $query = "SELECT * FROM `user_settings` WHERE `assoc_id` = '$term'";}
else
{
    $query = "SELECT * FROM `user_settings` WHERE `username` LIKE '%$term%' OR `prefix` LIKE '%$term%' OR `postfix` LIKE '%$term%'";    
}


if ($result = $db->query($query)) {
    
    $num_results = $result->num_rows;
    if ($num_results > 1)
    {
        if (strlen($term) > 0)
        {
            echo '<h1>Player Search <small>('.$num_results.' results)</small></h1><p>';
        }
        else
        {
            echo '<h1>All Players ('.$num_results.')</h1><p>';
        }
        $player_info = array();
        /* fetch associative array */
        while ($row = $result->fetch_assoc()) {
             //printf ("<li>%s %s %s (%s)</li>\n", $row["prefix"], $row["username"],$row["postfix"],$row["status"]);
             $player_id = $row['assoc_id'];
             $player_info["/psearch/$player_id/"] =  $row['prefix'] .' '. $row['username'] . ' ' .  $row['postfix'] . ' (' . $row['status'] . ')';
        }
        echo player_options($player_info);
    }
    elseif ($num_results == 1)
    {
        echo '<h1>Player Overview</h1><p>';
        while ($row = $result->fetch_assoc()) {
            $lookup_id = $row['assoc_id'];
            $user_lookup = new user($lookup_id);
            $user_info[$lookup_id] = $user_lookup->load_tables('user_stats',1);
            print $user_lookup->display_info($user_info[$lookup_id]);
            // printf ("<li>%s </li>\n", $user_info[$lookup_id]['username']);
        }
    }
    else
    {
        echo '<h1>Player Search <small>('.$num_results.' results)</small></h1><p>';
        echo 'No players found!';
    }
    /* free result set */
    $result->close();
}

echo html_form('/psearch/',"<input name=\"q\"><input value=\"Search\" type=\"submit\">");
?>